package com.bawei.module_mine.viewmodel

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.mvi.base.BaseViewModel
import com.bawei.lib_net.entity.ResponseEntity
import com.bawei.module_mine.intent.QuickLoginIntent
import com.bawei.module_mine.model.entity.UserEntity
import com.bawei.module_mine.model.service.UserCenterService
import com.bawei.module_mine.state.QuickLoginState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class QuickLoginViewModel : BaseViewModel<QuickLoginIntent>() {
    
    private val TAG = "QuickLoginViewModel"
    var phone: String = ""
    
    private val userCenterService by lazy {
        UserCenterService()
    }
    
    private val _state = MutableStateFlow<QuickLoginState>(QuickLoginState.QuickLoginInit)
    val state: StateFlow<QuickLoginState>
        get() = _state

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect {
                when (it) {
                    is QuickLoginIntent.OneKeyLogin -> doOneKeyLogin(it)
                    is QuickLoginIntent.GetPhoneNumber -> getPhoneNumber()
                    is QuickLoginIntent.CheckAuthService -> checkAuthService()
                }
            }
        }
    }

    /**
     * 执行一键登录
     */
    private fun doOneKeyLogin(intent: QuickLoginIntent.OneKeyLogin) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                withContext(Dispatchers.Main) {
                    _state.value = QuickLoginState.Loading("正在登录...")
                }
                // 调用你自己的接口
                val result: ResponseEntity<UserEntity> = userCenterService.quickLoginJG(loginToken = intent.loginToken, exID = "1")
                Log.d(TAG, "一键登录接口返回: code=${result.code}, msg=${result.msg}, data=${result.data}")
                withContext(Dispatchers.Main) {
                    if (result.code == 200 && result.data != null && !result.data.token.isNullOrEmpty()) {
                        _state.value = QuickLoginState.OneKeyLoginSuccess(result.data)
                    } else {
                        val failMsg = when {
                            result.data == null -> "用户信息为空"
                            result.data.token.isNullOrEmpty() -> "token为空"
                            else -> result.msg ?: "登录失败，请重试"
                        }
                        _state.value = QuickLoginState.OneKeyLoginFailed(failMsg)
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    _state.value = QuickLoginState.OneKeyLoginFailed("网络异常，请检查网络连接")
                }
            }
        }
    }

    /**
     * 获取手机号
     */
    private fun getPhoneNumber() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                Log.d(TAG, "开始获取手机号")
                
                withContext(Dispatchers.Main) {
                    _state.value = QuickLoginState.Loading("正在获取手机号...")
                }
                
                // 这里调用运营商认证服务获取手机号
                val phoneNumber = getSimulatedPhoneNumber()
              phone=phoneNumber
                withContext(Dispatchers.Main) {
                    if (phoneNumber.isNotEmpty()) {
                        Log.d(TAG, "获取手机号成功: $phoneNumber")
                        _state.value = QuickLoginState.PhoneNumberSuccess(phoneNumber)
                    } else {
                        Log.d(TAG, "获取手机号失败")
                        _state.value = QuickLoginState.PhoneNumberFailed("无法获取手机号，请检查SIM卡")
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "获取手机号异常: ${e.message}", e)
                withContext(Dispatchers.Main) {
                    _state.value = QuickLoginState.PhoneNumberFailed("获取手机号失败: ${e.message}")
                }
            }
        }
    }

    /**
     * 检查认证服务
     */
    private fun checkAuthService() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                Log.d(TAG, "检查认证服务")
                
                // 检查运营商认证服务是否可用
                val isAvailable = checkAuthServiceAvailability()
                
                withContext(Dispatchers.Main) {
                    if (isAvailable) {
                        Log.d(TAG, "认证服务可用")
                        _state.value = QuickLoginState.AuthServiceResult(true, "认证服务正常")
                    } else {
                        Log.d(TAG, "认证服务不可用")
                        _state.value = QuickLoginState.AuthServiceResult(false, "认证服务不可用，请使用其他登录方式")
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "检查认证服务异常: ${e.message}", e)
                withContext(Dispatchers.Main) {
                    _state.value = QuickLoginState.AuthServiceResult(false, "检查认证服务失败: ${e.message}")
                }
            }
        }
    }

    /**
     * 模拟获取手机号（实际项目中应该使用运营商SDK）
     */
    private fun getSimulatedPhoneNumber(): String {
        // 这里应该调用真实的运营商认证服务
        // 例如：移动、联通、电信的SDK
        return "138****8000" // 模拟返回的手机号
    }

    /**
     * 检查认证服务可用性（实际项目中应该检查运营商SDK）
     */
    private fun checkAuthServiceAvailability(): Boolean {
        // 这里应该检查真实的运营商认证服务
        // 例如：检查网络、检查SDK初始化状态等
        return true // 模拟服务可用
    }
} 